#include "mainwindow.h"
#include "eview.h"
#include <QtGui>
#include <QtOpenGL/QGLWidget>
#include <QList>
#include "thingy.h"
#include "being.h"
#include "zookeper.h"
#include "common.h"
#include <QGraphicsTextItem>
#include <QTextStream>
#include <QMap>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    //view
    amount = 0;
    view = new EView(this);
    scene = new QGraphicsScene();
    view->setScene(scene);
    view->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
    view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    view->show();
    view->setDisabled(true);
    connect(view,SIGNAL(itemClicked(QGraphicsItem*)),this,SLOT(itemClicked(QGraphicsItem*)));
    setCentralWidget(view);
    setWindowTitle(tr("Prymitywna symulacja ewolucji"));
    createActions();
    createToolBars();
    //toolbar
    showConnector();

}

void MainWindow::showConnector()
{
    connector = new Connector(this);
    connect(connector, SIGNAL(rejected()),SLOT(quit()));
    connector->setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
    if (connector->exec() == QDialog::Accepted)
    {
        qSize->setEnabled(true);
        actBegin->setEnabled(true);
        nameLabel->setEnabled(true);
    }
    else
        exit(0);
}

void MainWindow::quit()
{
    exit(0);
}

void MainWindow::createActions()
//! [17] //! [18]
{
    actBegin = new QAction(tr("&Stwórz planszę"), this);
    actBegin->setShortcuts(QKeySequence::New);
    actBegin->setStatusTip(tr("Stwórz planszę."));
    connect(actBegin, SIGNAL(triggered()), this, SLOT(begin()));

    actPlay = new QAction(tr("&Play"), this);
    //actPlay->setShortcuts(QKeySequence::);
    actPlay->setStatusTip(tr("Kontynuuj symulację."));
    actPlay->setDisabled(true);
    connect(actPlay, SIGNAL(triggered()), this, SLOT(play()));

    actPause = new QAction(tr("&Pause"), this);
    //actPause->setShortcuts(QKeySequence::New);
    actPause->setStatusTip(tr("Zatrzymaj symulację."));
    actPause->setDisabled(true);
    connect(actPause, SIGNAL(triggered()), this, SLOT(pause()));

    actStop = new QAction(tr("&Stop"), this);
    //actStop->setShortcuts(QKeySequence::New);
    actStop->setStatusTip(tr("Zakończ symulację."));
    actStop->setDisabled(true);
    connect(actStop, SIGNAL(triggered()), this, SLOT(stop()));

    actPopulate = new QAction(tr("&Ustal populację"), this);
    //actStop->setShortcuts(QKeySequence::New);
    actPopulate->setStatusTip(tr("Ustal początkowe warunki planszy."));
    actPopulate->setDisabled(true);
    connect(actPopulate, SIGNAL(triggered()), this, SLOT(populate()));
}

void MainWindow::createToolBars()
{
    nameLabel = new QLabel(tr("Rozmiar:"));
    nameLabel->setDisabled(true);
    createToolBar = addToolBar(tr("Create"));
    createToolBar->addWidget(nameLabel);
    qSize = new QSpinBox(createToolBar);
    qSize->setMinimum(3);
    qSize->setMaximum(1000);
    qSize->setDisabled(true);
    createToolBar->addWidget(qSize);
    createToolBar->addAction(actBegin);
    createToolBar->addAction(actPopulate);
    //createToolBar->setDisabled(true);
    controlToolBar = addToolBar(tr("Control"));
    controlToolBar->addAction(actPlay);
    controlToolBar->addAction(actPause);
    controlToolBar->addAction(actStop);
}

void MainWindow::begin()
{
    qSize->setDisabled(true);
    actBegin->setDisabled(true);
    nameLabel->setDisabled(true);
    actPopulate->setEnabled(true);

    resetHex();
    populist = new QList<Being *>();
    int margin,size = 10;
    int number = qSize->value();
    amount = number;
    connector->createMeadow(number);

    hItems = new HexItem**[number];
    for (int i = 0; i < number; ++i)
        hItems[i] = new HexItem*[number];

    texts = new QGraphicsTextItem**[number];
    for (int i = 0; i < number; ++i)
        texts[i] = new QGraphicsTextItem*[number];

    const double h = sqrt(3) * size;
    bool odd = false;
    //Populate the scene
    for (int j = 0; j < number * 2; ++j)
    {
        if (odd)
        {
            margin = size * 2;
            for(int i = 0; i < ((number + 1) / 2); ++i) {
               HexItem* hex;
               //QGraphicsTextItem* text;
               hex = (hItems[i * 2][(j - 1) / 2] = new HexItem(0,size,h));
               //text = (texts[i * 2][(j - 1) / 2] = new QGraphicsTextItem(tr("0")));
               hex->setMeadow(connector->common->meadow, i * 2,(j - 1) / 2);
               //hex->updateGrass();
               scene->addItem(hex);
               //scene->addItem(text);
               hex->setPos(margin + (size * 6 * i), h + j * h);
               //text->setPos(margin + (size * 6 * i), h + j * h);
            }
        }
        else
        {
            margin = size * 5;
            for(int i = 0; i < number / 2; ++i) {
                HexItem* hex;
                //QGraphicsTextItem* text;
                hex = (hItems[1 + i * 2][j / 2] = new HexItem(0,size,h));
                //text = (texts[1 + i * 2][j / 2] = new QGraphicsTextItem(tr("0")));
                hex->setMeadow(connector->common->meadow, 1 + i * 2, j / 2);
                //hex->updateGrass();
                scene->addItem(hex);
                //scene->addItem(text);
                hex->setPos(margin + (size * 6 * i), h + j * h);
                //text->setPos(margin + (size * 6 * i), h + j * h);
            }
        }
        odd = !odd;
    }

    view->setSceneRect(0, 0, size + (number/2) * size * 6,h + h * number * 2);
    view->SetCenter(QPointF(number * size * 2, h * number));
    view->setEnabled(true);
    zooKeeper = new ZooKeeper(scene, hItems);
    connector->myerl->zooKeeper = zooKeeper;
}


void MainWindow::play()
{
    connector->play();
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(60);
    actPlay->setDisabled(true);
    actPause->setEnabled(true);
    actStop->setEnabled(true);
}

void MainWindow::pause()
{
    connector->pause();
    timer->stop();
    actPlay->setEnabled(true);
    actPause->setDisabled(true);
}

void MainWindow::stop()
{
    connector->stop();
    timer->stop();
    actPause->setDisabled(true);
    actPlay->setDisabled(true);
    actStop->setDisabled(true);
    createToolBar->setEnabled(true);
    nameLabel->setEnabled(true);
    actBegin->setEnabled(true);
    qSize->setEnabled(true);
    delete zooKeeper;
}


void MainWindow::update()
{
    for (int i = 0; i < amount; i++)
    {
        for (int j = 0; j < amount; j++)
        {
            hItems[i][j]->paint();
            //QString pointString;
            //QTextStream stream(&pointString);
            //stream << connector->common->meadow->getField(i,j);
            //texts[i][j]->setPlainText(pointString);
        }
    }
}

void MainWindow::resetHex()
{
    QList<QGraphicsItem *> list = scene->items();
        QList<QGraphicsItem *>::Iterator it = list.begin();
        for (; it != list.end(); ++it) {
            if ( *it )
                delete *it;
        }
    for (int i = 0; i < amount; ++i)
        delete[] hItems[i];
    if (amount != 0)
        delete[] hItems;
}

void MainWindow::itemClicked(QGraphicsItem *item)
{
   if (actPopulate->isEnabled() || (actPlay->isEnabled() && actStop->isEnabled()))
   if (HexItem* hex = qgraphicsitem_cast<HexItem *>(item))
   {
       if (actPopulate->isEnabled())
       {
           if (hex->circle == NULL)
           {
               Being *being = new Being(0, hex->h);
               Thingy *dialog = new Thingy(0, being, 0);
               if (dialog->exec() == 1)
               {
                   being->X = hex->getX();
                   being->Y = hex->getY();
                   being->setPos(hex->pos());
                   scene->addItem(being);
                   being->show();
                   hex->circle = being;
                   populist->append(being);
               }
           }
           else
           {
               Thingy *dialog = new Thingy(0, hex->circle, 1);
               if (dialog->exec() == -1)
               {
                   populist->removeAt(populist->indexOf(hex->circle));
                   scene->removeItem(hex->circle);
                   delete hex->circle;
                   hex->circle = NULL;
               }
           }
       }
       else
       {
           foreach (Being* b, *(zooKeeper->beings))
                if (b->pos() == hex->pos())
                {
                     Thingy *dialog = new Thingy(0, b, -1);
                     dialog->exec();
                }

       }
   }
}

MainWindow::~MainWindow()
{

}

void MainWindow::populate()
{
    actPlay->setEnabled(true);
    actPopulate->setDisabled(true);

    QList<Being *>::Iterator it = populist->begin();
    for (; it != populist->end(); ++it) {
            if ( *it )
            {
                connector->newThingy((*it)->X,(*it)->Y,(*it)->typeOf,(*it)->spawnW,(*it)->minW,(*it)->weight,(*it)->speed);
                scene->removeItem(*it);
                delete *it;
            }
        }
    delete populist;

}


